// merchant//flyer/oneStaffFlyer/index.js
const utils = require('../../../utils/util.js')
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    flyerid: 0,
    allFlyerId: '',
    showTemplateImg: '',
    couponTypeList: [],
    flyerCardItemList: [],
    hasPre: false,
    hasNext: false,
    cardId: 0,
    avater: '',
    company: '',
    startY: 0,
    endY: 0,
    mobile: '',
    createUid: 0,
    source: 0
  },

  //获取手机号
  getPhoneNumber: function (e) {
    let that = this;
    utils.getMobile(e, function (callback) {
      if (callback) {
        that.setData({
          mobile: callback
        })
        that.receivePackage();
      } else {
        that.showToast({
          title: '请授权手机号',
          mask: true
        })
      }
    });
  },

  toDetails: function () {
    wx.reLaunch({
      url: '/pages/index/index?id=' + this.data.cardId,
    })
  },

  // 切换活动（点击展向上或向下的按钮）
  changeFlyer: function (e) {
    let tpye = e.currentTarget.dataset.type;
    let flyerid = this.data.flyerid;
    let allFlyerId = this.data.allFlyerId;
    let index = allFlyerId.indexOf(flyerid);
    this.data.flyerid = allFlyerId[index + 1];
    if (tpye == 'pre') {
      this.data.flyerid = allFlyerId[index - 1];
    }
    this.setNextOrPre(this.data.flyerid);
    this.getPackInfo(this.data.flyerid);
  },

  // 切换活动（上下滑动操作）
  changeFlyerByTouch: function (touchType) {
    let tpye = touchType;
    let flyerid = this.data.flyerid;
    let allFlyerId = this.data.allFlyerId;
    let index = allFlyerId.indexOf(flyerid);
    this.data.flyerid = allFlyerId[index + 1];
    if (tpye == 'pre') {
      this.data.flyerid = allFlyerId[index - 1];
    }
    this.setNextOrPre(this.data.flyerid);
    this.getPackInfo(this.data.flyerid);
  },

  setNextOrPre: function (flyerid) {
    let hasPre = false;
    let hasNext = false;
    let allFlyerId = this.data.allFlyerId;
    let currentIndex = allFlyerId.indexOf(flyerid);//当前商家的活动下标
    if (currentIndex > 0) {
      hasPre = true;
    }
    if (allFlyerId.length > 1) {
      if (currentIndex != allFlyerId.length - 1) {
        hasNext = true;
      }
    }
    this.setData({
      hasPre: hasPre,
      hasNext: hasNext
    })
  },

  touchstart: function (e) {
    if (e.touches.length == 1) {
      this.data.startY = e.touches[0].clientY;
    }
  },

  touchend: function (e) {
    let that = this;
    if (e.changedTouches.length == 1) {
      let endY = e.changedTouches[0].clientY;
      var disY = that.data.startY - endY;
      if (disY >= 1 && that.data.hasNext) {//上滑
        that.changeFlyerByTouch('next');
      } else if (disY < -1 && that.data.hasPre) { //下拉
        that.changeFlyerByTouch('pre');
      }
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('单礼包',options);
    let params = decodeURIComponent(options.scene);
    if (params && params != 'undefined') {//扫描小程序二维码进
      let plist = '';
      let param = params.match(/p-(\S*)/)[1];//参数
      plist = param.split('_');
      this.data.flyerid = plist[0];
      this.getPackInfo(plist[0]);
      this.data.source = 1;
    }
    // 测试测试
    // if (options.isTest) {
    //   this.data.flyerid = options.flyerid;
    //   this.data.source = 1;
    //   this.getPackInfo(options.flyerid);
    //   return;
    // }
    if (options.flyerid) {
      this.data.flyerid = options.flyerid;
      let allFlyerId = options.allFlyerId;
      this.data.allFlyerId = allFlyerId.split(',');
      this.setNextOrPre(options.flyerid);
      this.getPackInfo(options.flyerid);
    }
  },

  // 获取当前活动商家信息
  getStaffInfo: function (uid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Staff/GetStaffIdByUid?uid=' + uid,
      success: function (res) {
        if (res.data.Code == 0) {
          let avater = utils.formatAvater(res.data.Data.Avater, 'https://static.711688.net.cn/upload/card/source/');
          that.data.cardId = res.data.Data.Id;
          if (that.data.source > 0) {
            that.bindClient()
          }
          that.setData({
            avater: avater,
            company: res.data.Data.Company
          })
        }
      }
    })
  },
  // 绑定关系
  bindClient: function () {
    let that = this;
    if (app.globalData.userInfo) {
      if (app.globalData.userInfo.Mobile) {
        that.setData({
          mobile: app.globalData.userInfo.Mobile
        })
      }
      wx.request({
        url: app.globalData.host + '/api/BusinessCard/BindClient?staffId=' + that.data.cardId + '&uid=' + app.globalData.userInfo.Uid + '&source=' + that.data.source + '&shareUid=' + that.data.createUid,
        success: function (res) {
        }
      })
    } else {
      setTimeout(function () {
        that.bindClient();
      }, 1000)
    }
  },

  // 获取当前活动卡券
  getPackInfo: function (flyerid) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Leaflet/GetGradePackageInfo?gradeId=' + flyerid,
      success: function (res) {
        if (res.data.Code == 0) {
          let couponTypeList = res.data.Data.couponTypeList;
          let cardItemList = res.data.Data.cardItemList;
          let showTemplateImg = '';
          if (cardItemList.length > 0) {
            for (let j = 0; j < cardItemList.length; j++) {
              var detailpics = cardItemList[j].DetailPics;
              cardItemList[j].showDetailPics = '';
              var list = [];
              if (detailpics != '') {
                var newDetailPics = detailpics.split(",");
                for (let k = 0; k < newDetailPics.length; k++) {
                  list[k] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[k];
                }
                cardItemList[j].showDetailPics = list[0];
              }
            }
          }
          if (couponTypeList.length > 0) {
            let date = new Date();
            for (let i = 0; i < couponTypeList.length; i++) {
              var date2 = new Date(Date.parse(couponTypeList[i].sendendtime.replace(/-/g, "/")));
              if (date2 < date) {
                couponTypeList[i].isExpiretime = 1;
              } else {
                couponTypeList[i].isExpiretime = 0;
              }
              couponTypeList[i].sendstarttime = couponTypeList[i].sendstarttime.substr(0, 10);
              couponTypeList[i].sendendtime = couponTypeList[i].sendendtime.substr(0, 10);
              var detailpics = couponTypeList[i].DetailPics;
              couponTypeList[i].showDetailPics = '';
              var list = [];
              if (detailpics != '') {
                var newDetailPics = detailpics.split(",");
                for (let k = 0; k < newDetailPics.length; k++) {
                  list[k] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[k];
                }
                couponTypeList[i].showDetailPics = list[0];
              }
            }
          }
          if (res.data.Data.grade) {
            that.data.createUid = res.data.Data.grade.Uid;
            that.getStaffInfo(res.data.Data.grade.Uid);
            let template = res.data.Data.grade.Template;
            if (template) {
              showTemplateImg = utils.formatAvater(template, 'https://static.711688.net.cn/upload/share/');
            }
          }
          that.setData({
            flyerCardItemList: cardItemList,
            couponTypeList: couponTypeList,
            showTemplateImg: showTemplateImg
          })
        }
      }
    })
  },

  // 优惠券详情
  toCouponDetail: function (e) {
    let coupontypeid = e.currentTarget.dataset.coupontypeid;
    wx.navigateTo({
      url: '/merchant/merchants/cardDetails/index?type=1&coupontypeid=' + coupontypeid,
    })
  },
  // 消费卡详情
  toCardItemDetail: function (e) {
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/merchant/merchants/cardDetails/index?type=2&ids=' + id,
    })
  },
  receivePackage: function () {
    let that = this;
    // console.log(app.globalData.userInfo.Uid);
    // console.log(that.data.createUid);
    // console.log(that.data.flyerid);
    // return;
    wx.showLoading({
      title: '正在领取',
      mask: true
    })
    wx.request({
      url: app.globalData.host + '/api/leaflet/Receive',
      data: {
        uid: app.globalData.userInfo.Uid,
        shareUid: that.data.createUid,
        gradeId: that.data.flyerid
      },
      method: 'POST',
      success: function (res) {
        wx.hideLoading();
        console.log(res);
        if (res.data.Code == 0) {
          wx.showToast({
            title: '领取成功',
            mask: true
          })
          wx.reLaunch({
            url: '/merchant/merchants/myCardCoupon/index'
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      },
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  }
})